// 账单列表相关的store
import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";

const billStore = createSlice({
    name: 'bill',
    // 数据状态
    initialState: {
        billList: []
    },
    // 同步修改方法
    reducers: {
        setBillList(state, action) {
            state.billList = action.payload
        },
        // 同步添加账单
        addBill(state, action) {
            state.billList.push(action.payload)
        },
    }
});

// 解构action，批量导出
const {setBillList, addBill} = billStore.actions;
// 编写异步
const getBillList = () => {
    return async (dispatch) => {
        // 异步请求
        const res = await axios.get("http://localhost:8888/ka");
        // 触发同步reducer
        dispatch(setBillList(res.data))
    }
}
const addBillList = (data) => {
    return async (dispatch) => {
        // 异步请求
        const res = await axios.post("http://localhost:8888/ka", data);
        // 触发同步reducer
        dispatch(addBill(res.data))
    }
}
export {getBillList, addBillList}

// 解构action，默认导出
const reducer = billStore.reducer;

export default reducer